package com.example.chessbattleplatform.web.chess_rooms.controller;

import com.example.chessbattleplatform.Pojo.Result.WebResult;
import com.example.chessbattleplatform.utils.ThreadJwtParseUtils;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.Vo.UpdateRoomVo;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.dto.JoinRoomDto;
import com.example.chessbattleplatform.web.chess_rooms.service.impl.RoomsServiceInterface;
import com.example.chessbattleplatform.web.chess_rooms.websocket.RoomsMemberWebSocketServer;
import com.example.chessbattleplatform.web.chess_rooms.websocket.RoomsWebSocketServer;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController

@RequestMapping("/api/chess-rooms")
@RequiredArgsConstructor
public class RoomsMemberController {
    private final RoomsServiceInterface roomsServiceInterface;
    private final ThreadJwtParseUtils threadJwtParseUtils;

    /**
     * 加入房间
     */
    @PostMapping("/members")
    public WebResult<UpdateRoomVo> JoinRoom(@Valid @RequestBody JoinRoomDto joinRoomDto) {

        log.info("加入房间{}", joinRoomDto);
        // 获取 用户 信息
        Long threadUserId = threadJwtParseUtils.getThreadUserId();
        UpdateRoomVo updateRoomVo = roomsServiceInterface.joinRoom(joinRoomDto.getRoomId(), threadUserId, joinRoomDto.getPassword());

        // webSocket 更新数据
        // 房间列表更新
        RoomsWebSocketServer.sendListQueriesMessage();

        // 更新所有用户房间信息
        RoomsMemberWebSocketServer.sendQueriesMessages();
        return WebResult.success(updateRoomVo);
    }

    /**
     * 退出房间
     */
    @DeleteMapping("/members")
    public WebResult<UpdateRoomVo> ExitRoom() {

        // 获取 用户 信息
        Long threadUserId = threadJwtParseUtils.getThreadUserId();
//        log.info("删除用户{}",threadUserId);
        UpdateRoomVo updateRoomVo = roomsServiceInterface.leaveRoom(threadUserId);
        // 更新所有用户房间信息
        RoomsMemberWebSocketServer.sendQueriesMessages();
        return WebResult.success(updateRoomVo);
    }
}
